package com.tool.web.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


@Aspect
@Component
public class LoggerAOP {

    private static Logger logger = LoggerFactory.getLogger(LoggerAOP.class.getName());


    @Pointcut("execution(* com.tool.web.controller..*.*(..)) && !execution(* com.tool.web.aop.*.*(..))")
    public void allMethodPointcut() {
    }

    /**
     * Print log before method invocation
     *
     * @param joinPoint
     */
    @Before("allMethodPointcut()")
    public void logBeforeMethod(JoinPoint joinPoint) {
        if (logger.isTraceEnabled()) {
            String methodName = joinPoint.getSignature().toString();
            String targetClass = joinPoint.getTarget().getClass().getName();
            String parameters = "";
            for (Object object : joinPoint.getArgs()) {
                if (object != null) {
                    parameters = parameters + object.toString() + ";";
                }
            }

            logger.trace("[METHOD LOG] Entering Class: [{}],method:[{}], ",
                    targetClass, methodName, parameters);

        }
    }

    /**
     * Print log after method invocation
     *
     * @param joinPoint
     */
    @After("allMethodPointcut() && args(retVal)")
    public void logAfterMethod(JoinPoint joinPoint, Object retVal) {
        if (logger.isTraceEnabled()) {
            String methodName = joinPoint.getSignature().toString();
            String targetClass = joinPoint.getTarget().getClass().getName();
            logger.trace(
                    "[METHOD LOG] Exiting Class: [{}],method:[{}],return value: [ {}]",
                    targetClass, methodName, retVal.toString());

        }
    }

}
